package com.lock;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;

/**
 * @author:wesley
 */
public class LockService {

    private String ipAddress = "192.168.56.130:2181";

    private int session_time = 10000;

    private String group_path = "/disLocks";

    ZookeeperCommon ac = new ZookeeperCommon();

    public void doService(DoServiceTemplate template){
        try {
            ZooKeeper zk = ac.connect(ipAddress, session_time);

            //分布式锁
            DistributedLock distributedLock = new DistributedLock(zk);

            //观察锁，在适当时候进行操作
            LockWatch watch = new LockWatch(distributedLock, template);

            //给锁设置观察事件
            distributedLock.setWatcher(watch);

            //创建根节点
            distributedLock.createGroupNode(group_path, "节点："+Thread.currentThread().getName());

            //获取锁
            boolean lock = distributedLock.getLock();
            if (lock) {
                watch.doSometime("lockService");
                //解锁
                distributedLock.unlock();
            }

        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (KeeperException e) {
            e.printStackTrace();
        }


//        System.out.println("当前线程："+Thread.currentThread().getName());

    }






}


